package com.myk.game.heroscuffle.game;

import android.util.Log;

import com.blankj.utilcode.util.LogUtils;
import com.blankj.utilcode.util.ThreadUtils;
import com.myk.game.heroscuffle.utils.ThreadUtil;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * 游戏相关的线程工具
 */
public class GameExecutor {

    private final Object lock = new Object(); //线程的锁对象
    private final Game game; //当前游戏状态、

    public GameExecutor(Game game) {
        this.game = game;
    }

    //执行一段动画，在子线程发生异常时会提示错误信息
    public void submit(Runnable runnable) {
        new Thread(() -> {
            try {
                runnable.run();
            }
            catch (Exception e) {
                LogUtils.e("*游戏流程发生异常*");
                String expInfo = "当前回合：" + game.round + "," +
                        "当前行动英雄：" + (game.pool.curActionHero == null ? "null" : game.pool.curActionHero.NAME) + "\n" +
                        "异常信息->" + Log.getStackTraceString(e);
                LogUtils.e(expInfo);
                String errInfo = "当前回合：" + game.round + "\n" +
                        "当前行动英雄：" + (game.pool.curActionHero == null ? "null" : game.pool.curActionHero.NAME) + "\n" +
                        "异常信息->" + e.getMessage();
                game.ui.saveErrorRecordData(expInfo);
                game.ui.showErrorDialog(errInfo);
            }
        }).start();
    }

    //代码阻塞到当前位置，直到有代码执行resume
    public void pause() {
        synchronized (lock) {
            try {
                lock.wait();
            }
            catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

    //释放pause的阻塞
    public void resume() {
        synchronized (lock) {
            lock.notifyAll();
        }
    }
}
